/**
 * 
 */

package com.wutianyi.thrift.example;

import java.io.IOException;

import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import com.wutianyi.thrift.shared.SharedStruct;
import com.wutianyi.thrift.tutorial.Calculator;
import com.wutianyi.thrift.tutorial.InvalidOperation;
import com.wutianyi.thrift.tutorial.Operation;
import com.wutianyi.thrift.tutorial.Work;
import com.wutianyi.thrift.tutorial.Calculator.Client;

/**
 * @author wutianyi
 * 
 */
public class JavaClient {

	public static void main(String[] args) throws TTransportException, IOException, InterruptedException {

		TTransport transport = new TSocket("localhost", 9090);
		try {
			transport.open();
		}catch(TTransportException e) {
			e.printStackTrace();
		}
		TProtocol protocol = new TBinaryProtocol(transport);
		Calculator.Client client = new Calculator.Client(protocol);
		
		perform(client);
		Thread.sleep(10000);
		perform(client);
		transport.close();
	}

	/**
	 * @param client
	 */
	private static void perform(Client client) {

		try {
			client.ping();
			System.out.println("ping()");
			int sum = client.add(1, 1);
			System.out.println("1 + 1 = " + sum);
			Work work = new Work();
			work.num1 = 1;
			work.num2 = 2;
			try {
				
				int quotient = client.calculate(1, work);
				System.out.println("Whoa we can divide by 0");
			} catch(TApplicationException e) {
//				System.out.println(e.getWhat() + " : " + e.getWhy());
			}

			work.op = Operation.SUBTRACT;
			work.num1 = 15;
			work.num2 = 10;

			int diff = client.calculate(1, work);
			System.out.println("15 - 10 = " + diff);

			SharedStruct log = client.getStruct(1);
			System.out.println("Check log: " + log.value);
		}catch(TException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(InvalidOperation e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
